<script>
import {
  defineComponent,
  ref,
  watch,
  computed,
  onUnmounted,
  reactive,
  provide,
  onMounted,
} from 'vue'
import { useRouter, useRoute, RouterLink } from 'vue-router'
import {
  UserOutlined,
  MessageOutlined,
  CloudUploadOutlined,
  EyeOutlined,
} from '@ant-design/icons-vue'
import { getUserInfo, clearUserInfo } from '@Config/server/localStorage'
import { LogOut } from '@Config/server/api'
import { Messages, wss } from '@Config/config'
import CreateMenu from '@Components/createMenu'
import { IconWeiXin } from '@Assets/fonts/svg'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import Breadcrumb from '@Components/breadcrumb'
import { useStore } from 'vuex'
import obHooks from '@Page/user/obHooks'
import { setItem, getItem } from '@Config/server/localStorage'
import { getDomAttributeByFolderId } from '@Untils'
import { useWin } from '@Hooks/win'
import UserInfoFrom from '@Page/user/userInfo'
const App = defineComponent({
  components: {
    UserOutlined,
    IconWeiXin,
    RouterLink,
    MessageOutlined,
    Breadcrumb,
    CreateMenu,
    CloudUploadOutlined,
  },
  setup(props, context) {
    const router = useRouter()
    const route = useRoute()
    var infos = getUserInfo()
    //未登录直接跳到登录页面
    if (infos == null) {
      router.push({ path: '/' })
    }
    let user = ref({ name: infos?.username })

    //当路由发生变化时，清除消息提示
    let _watch = watch(
      () => route.path,
      () => {
        Messages.clear()
      }
    )
    onUnmounted(() => {
      _watch()
    })
    //退出
    const logOutHandler = async () => {
      let result = await LogOut()
      if (result.code == 0) {
        clearUserInfo()
        router.replace({ path: '/' })
        router.removeRoute('management')
      }
    }
    Messages.clear()
    //用户角色
    let roleList = computed(() => {
      let _list = getUserInfo()?.roleNameList || []
      return (
        <a-menu>
          <a-menu-item>
            {_list.map((x) => {
              return <a-tag color="pink">{x}</a-tag>
            })}
          </a-menu-item>
        </a-menu>
      )
    })

    let menu_ui = reactive({
      data: null,
    })

    provide('rightIconMenu', menu_ui)
    let store = useStore()

    let cancelHandler = () => {
      store.commit('preivew', {
        visible: false,
        src: null,
      })
    }

    let rmenu = ref()
    let rmenuRef = ref()
    let current_node = ref(null)
    onMounted(() => {
      document.oncontextmenu = function(e) {
        if (current_node.value) {
          current_node.value.style.backgroundColor = null
        }
        if (e.rightMenu) {
          let { dom, dataId } = getDomAttributeByFolderId(e)

          if (dataId) {
            dom.style.backgroundColor = 'rgb(204,232,255)'
            current_node.value = dom
          }

          rmenu.value = e.rightMenu
          rmenuRef.value.style.left = e.x + 'px'
          rmenuRef.value.style.top = window.scrollY + e.y + 'px'
          rmenuRef.value.style.display = 'block'
          setTimeout(() => {
            /**
             *
             * 纠正弹出层的问题，尽量不要超出当前显示的区域
             */
            let menu_height = e.rightMenu.el.offsetHeight //菜单高度
            let menu_width = e.rightMenu.el.offsetWidth //菜单高度
            let screen_height = document.body.clientHeight
            let screen_width = document.body.clientWidth
            if (menu_height + e.y > screen_height) {
              let reduce_num = menu_height + e.y - screen_height
              rmenuRef.value.style.top =
                window.scrollY + e.y - reduce_num + 'px'
            }
            if (menu_width + e.x > screen_width) {
              let reduce_num2 = menu_width + e.x - screen_width
              rmenuRef.value.style.left = e.x - reduce_num2 + 'px'
            }
          })
          return false
        } else {
          rmenuRef.value.style.display = 'none'

          return true
        }
      }

      document.addEventListener('click', () => {
        rmenuRef.value ? (rmenuRef.value.style.display = 'none') : null
        if (current_node.value) {
          current_node.value.style.backgroundColor = null
          current_node.value = null
        }
      })
    })
    onUnmounted(() => {
      document.oncontextmenu = null
    })

    let defaultViews = ref(getItem('preview_type') || 'middle')
    let changeHandler = (e) => {
      defaultViews.value = e
      store.commit('folderUi', defaultViews.value)
    }

    let { add } = obHooks()
    provide('addInterSectionObs', add)

    let [useInfoWin] = useWin({
      component: <UserInfoFrom />,
      attr: {
        title: '个人资料',
      },
    })
    let userInfoHandler = () => {
      useInfoWin({})
    }

    return {
      store,
      user,
      logOutHandler,
      router,
      roleList,
      menu_ui,
      cancelHandler,
      rmenu,
      rmenuRef,
      changeHandler,
      defaultViews,
      route,
      userInfoHandler,
    }
  },

  render() {
    return (
      <a-config-provider locale={zhCN}>
        <a-layout>
          <a-layout-header class="header">
            <div class="logo">
              <span style={{ 'font-size': '16px', 'font-weight': 'bold' }}>
                高速网盘
              </span>
            </div>
            <div>
              <a-space>
                <a-space>
                  <UserOutlined />
                  <a-button type="link" onClick={this.userInfoHandler}>
                    {this.user.name}
                  </a-button>
                </a-space>

                <a-button
                  type="link"
                  onClick={() => {
                    this.logOutHandler()
                  }}
                >
                  退出
                </a-button>
                {this.menu_ui.data != null && (
                  <a-dropdown
                    vSlots={{
                      overlay: () => {
                        if (typeof this.menu_ui.data == 'function') {
                          return this.menu_ui.data()
                        } else {
                          return (
                            <a-menu>
                              {this.menu_ui.data?.map((x) => {
                                return x.ui
                              })}
                            </a-menu>
                          )
                        }
                      },
                    }}
                  >
                    <a-button
                      shape="circle"
                      title="基本操作"
                      vSlots={{
                        icon: () => {
                          return <CloudUploadOutlined />
                        },
                      }}
                    ></a-button>
                  </a-dropdown>
                )}

                {this.route.meta.showEyes && (
                  <a-dropdown
                    vSlots={{
                      overlay: () => {
                        return (
                          <div
                            style={{
                              display: 'flex',
                              justifyContent: 'flex-end',
                            }}
                          >
                            <a-menu selectedKeys={[this.defaultViews]}>
                              <a-menu-item key="large">
                                <a-button
                                  type="link"
                                  onClick={() => {
                                    this.changeHandler('large')
                                  }}
                                >
                                  大图标
                                </a-button>
                              </a-menu-item>
                              <a-menu-item key="middle">
                                <a-button
                                  type="link"
                                  onClick={() => {
                                    this.changeHandler('middle')
                                  }}
                                >
                                  中等图标
                                </a-button>
                              </a-menu-item>
                              <a-menu-item key="small">
                                <a-button
                                  type="link"
                                  onClick={() => {
                                    this.changeHandler('small')
                                  }}
                                >
                                  小图标
                                </a-button>
                              </a-menu-item>
                              <a-menu-item key="list">
                                <a-button
                                  type="link"
                                  onClick={() => {
                                    this.changeHandler('list')
                                  }}
                                >
                                  列表
                                </a-button>
                              </a-menu-item>
                            </a-menu>
                            {
                              //  <a-radio-group
                              //   onChange={this.changeHandler}
                              //   defaultValue="middle"
                              // >
                              //   <a-radio value="large">大图标</a-radio>
                              //   <a-radio value="middle">中等图标</a-radio>
                              //   <a-radio value="small">小图标</a-radio>
                              // </a-radio-group>
                            }
                          </div>
                        )
                      },
                    }}
                  >
                    <a-button
                      shape="circle"
                      title="预览风格"
                      vSlots={{
                        icon: () => {
                          return <EyeOutlined />
                        },
                      }}
                    ></a-button>
                  </a-dropdown>
                )}
              </a-space>
            </div>
          </a-layout-header>
          <a-layout>
            <a-layout-sider style={{ background: '#fff' }} collapsible>
              <CreateMenu />
            </a-layout-sider>
            <a-layout style={{ padding: '0 24px 24px' }}>
              <Breadcrumb />
              <a-layout-content class="content">
                <router-view></router-view>
              </a-layout-content>
            </a-layout>
          </a-layout>
        </a-layout>

        <a-modal
          onCancel={this.cancelHandler}
          onOk={this.cancelHandler}
          visible={this.store.state.previewImage}
          width="100%"
          wrapClassName="full-modal"
          footer={null}
          destroyOnClose={true}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: 'calc( 100vh - 48px ) ',
              backgroundColor: '#fff',
            }}
          >
            <div style={{ position: 'fixed', right: '10px', bottom: '10px' }}>
              <a-button
                type="primary"
                onClick={() => {
                  location.href = this.store.state.preivewSrc + '?download=1'
                }}
              >
                下载
              </a-button>
            </div>
            <img
              src={this.store.state.preivewSrc}
              style={{ 'max-width': '100%', 'max-height': '100%' }}
            />
          </div>
        </a-modal>

        <div ref="rmenuRef" class="right_menu">
          {this.rmenu}
        </div>
      </a-config-provider>
    )
  },
})
export default App
</script>

<style scoped>
.content {
  background: #fff;
  padding: 24px;
  margin: 0;
  min-height: 580px;
  position: relative;
}
</style>

<style lang="less">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
</style>
